from PIL import Image
import numpy as np


def embed_watermark_bmp(input_path, watermark, output_path):
    # 读取BMP图像
    img = Image.open(input_path)
    if img.mode != 'RGB':
        img = img.convert('RGB')
    pixels = np.array(img)

    # 水印转为二进制（UTF-8编码）
    watermark_bin = ''.join(format(byte, '08b') for byte in watermark.encode('utf-8'))
    watermark_len = len(watermark_bin)

    # 检查容量（仅用R通道）
    max_capacity = pixels.shape[0] * pixels.shape[1]
    if watermark_len > max_capacity:
        raise ValueError(f"水印过长（{watermark_len}位），最大容量为{max_capacity}位")

    # 在R通道嵌入LSB
    watermark_index = 0
    for i in range(pixels.shape[0]):
        for j in range(pixels.shape[1]):
            if watermark_index < watermark_len:
                pixels[i, j, 0] = (pixels[i, j, 0] & 0xFE) | int(watermark_bin[watermark_index])
                watermark_index += 1
            else:
                break

                # 保存带水印图像
    Image.fromarray(pixels).save(output_path)


# 示例：嵌入当前时间水印
current_time = "leeTest2025-03-30"
embed_watermark_bmp("original.bmp", current_time, "watermarked.bmp")